<template>
  <el-scrollbar class="notice-list-scrollbar">
    <el-empty v-if="noticeList.length === 0 && !loading" description="暂无通知" />
    <el-card
      v-for="item in noticeList"
      :key="item.noticeId"
      class="notice-item"
      :class="{ unread: !item.read }"
      shadow="hover"
      @click="markAsRead(item)"
    >
      <div class="item-header">
        <div class="title-wrap">
          <el-icon class="icon">
            <BellFilled v-if="item.msgType === '2'" />
            <Box v-else-if="item.msgType === '1'" />
            <Edit v-else-if="item.msgType === '3'" />
            <ChatLineSquare v-else />
          </el-icon>
          <span class="title">{{ item.noticeTitle }}</span>
        </div>
        <el-tag size="small" :type="item.read ? 'info' : 'danger'" class="status">
          {{ item.read ? '已读' : '未读' }}
        </el-tag>
      </div>
      <div class="item-content">
        {{ item.noticeContent }}
      </div>
      <div class="item-footer">
        <span class="time">
          <el-icon><Clock /></el-icon>
          {{ formatTime(item.createTime) }}
        </span>
        <span class="creator">
          <el-icon><User /></el-icon>
          {{ item.createBy }}
        </span>
      </div>
    </el-card>
  </el-scrollbar>
  <div class="pagination-wrapper">
    <el-pagination
      background
      layout="prev, pager, next, jumper"
      :total="total"
      :page-size="pageSize"
      :current-page="currentPage"
      @current-change="handlePageChange"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue';
import { ElMessage } from 'element-plus';
import { BellFilled, Box, Edit, Clock, User, ChatLineSquare } from '@element-plus/icons-vue';
import { getUserNoticeList, markUserNoticeAsRead } from '../../../api/system/notice';

const props = defineProps<{
  type: string;
}>();

const emit = defineEmits<{
  (e: 'update-total', total: number, unreadInType: number): void;
  (e: 'mark-read'): void;
}>();

const noticeList = ref<any[]>([]);
const total = ref(0);
const currentPage = ref(1);
const pageSize = 10;
const loading = ref(false);

// 缓存各类型分页状态（避免切换 tab 后页码重置）
const pageCache = new Map<string, number>();

async function fetchList(page: number) {
  loading.value = true;
  try {
    getUserNoticeList({
      msgType: props.type,
      noticeType: '1',
      pageNum: page,
      pageSize: pageSize
    }).then((res: any) => {
      if (res.code === 200) {
        const rdata = res.rows || [];
        noticeList.value = rdata.map((item: any) => ({
          ...item,
          read: item.isRead === 1
        }));
        total.value = parseInt(res.total) || 0;
      }
    });
  } catch (error) {
    noticeList.value = [];
    total.value = 0;
  } finally {
    loading.value = false;
  }
}

function handlePageChange(page: number) {
  currentPage.value = page;
  pageCache.set(props.type, page);
  fetchList(page);
}

async function markAsRead(item: any) {
  if (!item.read) {
    try {
      await markUserNoticeAsRead(item.noticeId);
      item.read = '1';
      emit('mark-read');
    } catch (error) {
      ElMessage.error('标记失败，请重试');
    }
  }
}

function formatTime(time: string) {
  return time ? new Date(time).toLocaleString() : '';
}

// 监听 type 变化，恢复或初始化分页
watch(
  () => props.type,
  (newType) => {
    currentPage.value = pageCache.get(newType) || 1;
    fetchList(currentPage.value);
  },
  { immediate: true }
);
</script>

<style scoped lang="scss">
.notice-list-scrollbar {
}

.notice-item {
  margin-bottom: 12px;
  cursor: pointer;
  transition: all 0.25s ease;

  &.unread {
    border-left: 4px solid #f56c6c;
    background: #fff7f7;
  }

  &:hover {
    transform: translateY(-2px);
  }

  .item-header {
    display: flex;
    justify-content: space-between;
    margin-bottom: 6px;
    align-items: center;

    .title-wrap {
      display: flex;
      align-items: center;
      gap: 6px;

      .icon {
        font-size: 18px;
        color: #666;
      }

      .title {
        font-weight: 600;
        font-size: 15px;
      }
    }
  }

  .item-content {
    font-size: 14px;
    color: #666;
    margin-bottom: 6px;
    line-height: 1.5;
  }

  .item-footer {
    font-size: 12px;
    color: #999;
    display: flex;
    justify-content: space-between;
    align-items: center;

    span {
      display: flex;
      align-items: center;
      gap: 4px;
    }
  }
}

.pagination-wrapper {
  margin-top: 16px;
  height: 30px;
  display: flex;
  justify-content: center;
}
</style>
